package com.nexgo.payment.action.readcard;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.CardInfo;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.PanTextWatcher;
import com.nexgo.payment.widget.TitleBuilder;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ReadCardFragment extends BaseFragment implements Action<ActionStep>, ReadCardContract.View, BaseFragment.DownTimerListener {
    private static final String TRANS_DATA = "trans_data";
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_prompt_card)
    TextView tvPromptCard;
    @BindView(R.id.edt_manual_pan)
    EditText edtManualPan;
    @BindView(R.id.tv_prompt_date)
    TextView tvPromptDate;
    @BindView(R.id.edt_manual_exp_date)
    EditText edtManualExpDate;
    @BindView(R.id.iv_swipe)
    ImageView ivSwipe;
    @BindView(R.id.iv_insert)
    ImageView ivInsert;
    @BindView(R.id.iv_tap)
    ImageView ivTap;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.tv_amount_tip)
    TextView tvAmountTip;
    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;
    Unbinder unbinder;
    private OnActionListener mListener;
    private ReadCardContract.Presenter mPresenter;

    public ReadCardFragment() {
    }

    /**
     * 读卡界面
     * @param transData
     * @return
     */
    public static ReadCardFragment newInstance(TransData transData) {
        ReadCardFragment fragment = new ReadCardFragment();
        Bundle args = new Bundle();
        args.putParcelable(TRANS_DATA, transData);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TransData transData = null;
        if (getArguments() != null) {
            transData = getArguments().getParcelable(TRANS_DATA);
        }
        new ReadCardPresenter(this, Repository.getInstance(), transData);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_read_card, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.use_bank_card))
                .build();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left})
    public void onClick(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mPresenter.destroy();
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.READ_CARD;
    }

    @Override
    public void setPresenter(ReadCardContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showAmount(String amount) {
        tvAmountTip.setVisibility(View.VISIBLE);
        String format = SysConstant.FUND_SYMBOL + StringUtils.formatAmount(amount, SysConstant.FUND_DIGITS);
        tvAmount.setText(format);
        tvAmount.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCountTime(int countTime) {
        setDownTimer(countTime, this);
    }

    @Override
    public void showReadCard(boolean manual, boolean swipe, boolean insert, boolean tap) {
        if (manual) {
            edtManualPan.setVisibility(View.VISIBLE);
            edtManualPan.addTextChangedListener(new PanTextWatcher(edtManualPan) {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    super.onTextChanged(s, start, before, count);
                    if (s.length() > 15 && s.length() < 24) {
                        btnConfirm.setEnabled(true);
                        btnConfirm.setBackgroundResource(R.drawable.btn_confirm);
                    } else {
                        btnConfirm.setBackgroundResource(R.drawable.gray_button);
                        btnConfirm.setEnabled(false);
                    }
                }
            });
            tvPromptDate.setVisibility(View.VISIBLE);
            tvPromptDate.setText(R.string.plz_input_card_ext_date);
            edtManualExpDate.setVisibility(View.VISIBLE);
            btnConfirm.setVisibility(View.VISIBLE);
            btnConfirm.setEnabled(false);
            btnConfirm.setOnClickListener(v -> mPresenter.importManualPan(edtManualPan.getText().toString(),
                    edtManualExpDate.getText().toString()));
        }
        ivSwipe.setVisibility(swipe ? View.VISIBLE : View.GONE);
        ivInsert.setVisibility(insert ? View.VISIBLE : View.GONE);
        ivTap.setVisibility(tap ? View.VISIBLE : View.GONE);
        StringBuilder sb = new StringBuilder();
        if (swipe) {
            sb.append(getString(R.string.swipe_card));
            if (insert) {
                sb.append(getString(R.string.add_insert_card));
            }
            if (tap) {
                sb.append(getString(R.string.add_tap_card));
            }
            if (manual) {
                sb.append(getString(R.string.add_manual));
            }
        } else if (insert) {
            sb.append(getString(R.string.insert_card));
            if (tap) {
                sb.append(getString(R.string.add_tap_card));
            }
            if (manual) {
                sb.append(getString(R.string.add_manual));
            }
        } else if (tap) {
            sb.append(getString(R.string.tap_card));
            if (manual) {
                sb.append(getString(R.string.add_manual));
            }
        } else {
            sb.append(getString(R.string.manual));
        }
        tvPromptCard.setText(sb.toString());
    }

    @Override
    public void showSwipeError() {
        ToastUtils.showToast(R.string.swipe_incorrect);
    }

    @Override
    public void showMultipleCards() {
        ToastUtils.showToast(R.string.multiple_cards);
    }

    @Override
    public void showUseICC() {
        ToastUtils.showToast(R.string.use_ic_card);
    }

    @Override
    public void showUseMag() {
        ToastUtils.showToast(getString(R.string.use_mag_card));
    }

    @Override
    public void showPriorityUseRf() {
        ToastUtils.showToast(getString(R.string.use_rf_card));
    }

    @Override
    public void showReadCardError() {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_FAIL, null));
        }
    }

    @Override
    public void showInputCardNoError() {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_FAIL, getString(R.string.input_card_no_format_err)));
        }
    }

    @Override
    public void showEmptyExpDate() {
        ToastUtils.showToast(getString(R.string.input_card_exp_date_is_empty));
    }

    @Override
    public void showExpDateFormatError() {
        ToastUtils.showToast(getString(R.string.input_card_exp_date_format_err));
    }

    @Override
    public void showTryOtherCommunication() {
        cancelDownTimer();
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_FAIL, getString(R.string.please_try_other_communication)));
        }
    }

    @Override
    public void showReadCardTimeout() {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_TIMEOUT, getString(R.string.read_card_time_out)));
        }
    }

    @Override
    public void showSuccessful(CardInfo cardInfo) {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, cardInfo));
        }
        mPresenter.stopReadCard();
        cancelDownTimer();
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDownTimer();
        unbinder.unbind();
        mPresenter.destroy();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            tvTitleRight.setText("0");
        }
    }

}
